package com.moonbird.springboot.Utils.ppt;

import com.alibaba.fastjson.JSONObject;

import java.io.IOException;

public class PPTGenerator {

    private static final String API_BASE_URL = "https://zwapi.xfyun.cn";
    private static final ApiClient client = new ApiClient(API_BASE_URL);

    public static String generatePPTs(String question) throws IOException, InterruptedException {
        // 输入个人appId
        String appId = "f9173867";
        String secret = "MTNjM2UxN2NkMmUyZTQzNDIxN2UxOGRm";
        long timestamp = System.currentTimeMillis() / 1000;
        String ts = String.valueOf(timestamp);

        System.out.println("开始生成PPT...");

        // 获得鉴权信息
        ApiAuthAlgorithm auth = new ApiAuthAlgorithm();
        String signature = auth.getSignature(appId, secret, timestamp);

        // 创建两个PPT并获取它们的SID
        String sid1 = createPPT(appId, ts, signature, question);

        // 检查两个PPT的生成进度，并获取它们的URL
        String pptUrl = checkProgress(appId, ts, signature, sid1);
        System.out.println("PPT1 URL: "+ pptUrl);

        // 获取并编码两个PPT文件
        //String base64PPT1 = client.downloadAndEncodePPT(pptUrl1);

        return pptUrl;
    }

    private static String createPPT(String appId, String ts, String signature, String question) throws IOException {
        String response = client.createPPT(appId, ts, signature, question);
        JSONObject createResult = JSONObject.parseObject(response);
        return createResult.getJSONObject("data").getString("sid");
    }

    private static String checkProgress(String appId, String ts, String signature, String sid) throws IOException, InterruptedException {
        int process = 0;
        String pptUrl = null;

        while (process < 100) {
            Thread.sleep(5000); // 等待5秒再检查进度
            String response = client.checkProgress(appId, ts, signature, sid);
            JSONObject progressResult = JSONObject.parseObject(response);
            process = progressResult.getJSONObject("data").getIntValue("process");
            pptUrl = progressResult.getJSONObject("data").getString("pptUrl");
        }

        return pptUrl;
    }
}
